package com.ruoyi.department.service.impl;

import java.io.IOException;
import java.util.*;
import java.util.stream.Collectors;

import com.github.pagehelper.PageHelper;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.department.domain.vo.DepartmentVO;
import com.ruoyi.departmentdisease.domain.DepartmentDisease;
import com.ruoyi.departmentdisease.mapper.DepartmentDiseaseMapper;
import com.ruoyi.disease.domain.Disease;
import com.ruoyi.disease.mapper.DiseaseMapper;
import com.ruoyi.userdisease.mapper.UserDiseaseMapper;
import com.ruoyi.wx.utils.PinyinUtil;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.ruoyi.department.mapper.DepartmentMapper;
import com.ruoyi.department.domain.Department;
import com.ruoyi.department.service.IDepartmentService;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;
import net.sourceforge.pinyin4j.PinyinHelper;

/**
 * 【科室】Service业务层处理
 *
 * @author ruoyi
 * @date 2025-07-02
 */
@Service
public class DepartmentServiceImpl implements IDepartmentService {
    @Autowired
    private DepartmentMapper departmentMapper;

    @Autowired
    private DiseaseMapper diseaseMapper;

    @Autowired
    private DepartmentDiseaseMapper departmentDiseaseMapper;

    @Autowired
    private UserDiseaseMapper userDiseaseMapper;

    /**
     * 查询【请填写功能名称】
     *
     * @param departmentId 【请填写功能名称】主键
     * @return 【请填写功能名称】
     */
    @Override
    public Department selectDepartmentByDepartmentId(Long departmentId) {
        return departmentMapper.selectDepartmentByDepartmentId(departmentId);
    }

    /**
     * 查询【请填写功能名称】列表
     *
     * @param department 【请填写功能名称】
     * @return 【请填写功能名称】
     */
    @Override
    public List<Department> selectDepartmentList(Department department) {
        return departmentMapper.selectDepartmentList(department);
    }

    /**
     * 新增【请填写功能名称】
     *
     * @param department 【请填写功能名称】
     * @return 结果
     */
    @Override
    public int insertDepartment(Department department) {
        String departmentType = department.getDepartmentType();
        String firstPinyinChar = PinyinUtil.getFirstPinyinChar(departmentType);
        department.setSort(firstPinyinChar);
        return departmentMapper.insertDepartment(department);
    }

    /**
     * 修改【请填写功能名称】
     *
     * @param department 【请填写功能名称】
     * @return 结果
     */
    @Override
    public int updateDepartment(Department department) {
        return departmentMapper.updateDepartment(department);
    }

    /**
     * 批量删除【请填写功能名称】
     *
     * @param departmentIds 需要删除的【请填写功能名称】主键
     * @return 结果
     */
    @Override
    @Transactional
    public int deleteDepartmentByDepartmentIds(Long[] departmentIds) {
        ArrayList<Long> diseaseIds = new ArrayList<>();
        for (Long departmentId : departmentIds) {
            DepartmentDisease departmentDisease = new DepartmentDisease();
            departmentDisease.setDepartmentId(departmentId);
            List<DepartmentDisease> departmentDiseases = departmentDiseaseMapper.selectDepartmentDiseaseList(departmentDisease);
            for (DepartmentDisease disease : departmentDiseases) {
                diseaseIds.add(disease.getDiseaseId());
            }
        }
        Long[] diseaseIdsArray = diseaseIds.toArray(new Long[0]);
        diseaseMapper.deleteDiseaseByDiseaseIds(diseaseIdsArray);
        departmentDiseaseMapper.deleteDepartmentDiseaseByDepartmentIds(departmentIds);
        userDiseaseMapper.deleteUserDiseaseByDiseaseIds(diseaseIdsArray);
        return departmentMapper.deleteDepartmentByDepartmentIds(departmentIds);
    }

    /**
     * 删除【请填写功能名称】信息
     *
     * @param departmentId 【请填写功能名称】主键
     * @return 结果
     */
    @Override
    public int deleteDepartmentByDepartmentId(Long departmentId) {
        return departmentMapper.deleteDepartmentByDepartmentId(departmentId);
    }

    /**
     * 查询所有科室病种
     *
     * @return
     */
    @Override
    public List<DepartmentVO> selectDepartment() {
        ArrayList<DepartmentVO> departmentVOS = new ArrayList<>();
        Department department = new Department();
        List<Department> departments = departmentMapper.selectDepartmentList(department);
        for (Department department1 : departments) {
            DepartmentVO departmentVO = new DepartmentVO();
            DepartmentDisease departmentDisease = new DepartmentDisease();
            departmentDisease.setDepartmentId(department1.getDepartmentId());
            ArrayList<Disease> diseases = new ArrayList<>();
            List<DepartmentDisease> departmentDiseases = departmentDiseaseMapper.selectDepartmentDiseaseList(departmentDisease);
            for (DepartmentDisease disease : departmentDiseases) {
                Disease disease1 = diseaseMapper.selectDiseaseByDiseaseId(disease.getDiseaseId());
                disease1.setDepartmentId(disease.getDepartmentId());
                diseases.add(disease1);
            }
            departmentVO.setDepartmentId(department1.getDepartmentId());
            departmentVO.setDepartmentType(department1.getDepartmentType());
            departmentVO.setDiseaseList(diseases);
            departmentVOS.add(departmentVO);
        }

        return departmentVOS;
    }

    @Override
    public int selectDepartment1() {
        List<Department> departments = departmentMapper.selectDepartmentList(new Department());
        return departments.size();
    }

    @Override
    public List<Disease> selectDiseaseByDepartment(DepartmentVO departmentVO) {
        DepartmentDisease departmentDisease = new DepartmentDisease();
        departmentDisease.setDepartmentId(departmentVO.getDepartmentId());
        List<DepartmentDisease> departmentDiseases = departmentDiseaseMapper.selectDepartmentDiseaseList(departmentDisease);
        ArrayList<Disease> diseases = new ArrayList<>();
        for (DepartmentDisease disease : departmentDiseases) {
            Disease disease1 = diseaseMapper.selectDiseaseByDiseaseId(disease.getDiseaseId());
            disease1.setDepartmentId(disease.getDepartmentId());
            diseases.add(disease1);
        }
        return diseases;
    }

    @Override
    public int selectDepartmentDiseaseList(DepartmentVO departmentVO) {
        DepartmentDisease departmentDisease = new DepartmentDisease();
        departmentDisease.setDepartmentId(departmentVO.getDepartmentId());
        List<DepartmentDisease> size = departmentDiseaseMapper.selectDepartmentDiseaseList(departmentDisease);
        return size.size();
    }

    /**
     * 模糊查询病种
     *
     * @param illness
     * @return
     */
    @Override
    public AjaxResult getIllness(String illness) {
        ArrayList<DepartmentVO> departmentVOS = new ArrayList<>();
        List<Department> departments = departmentMapper.selectDepartmentLikeName(illness);
        if (!departments.isEmpty()) {
            for (Department department1 : departments) {
                DepartmentVO departmentVO = new DepartmentVO();
                DepartmentDisease departmentDisease = new DepartmentDisease();
                departmentDisease.setDepartmentId(department1.getDepartmentId());
                ArrayList<Disease> diseases = new ArrayList<>();
                List<DepartmentDisease> departmentDiseases = departmentDiseaseMapper.selectDepartmentDiseaseList(departmentDisease);
                for (DepartmentDisease disease : departmentDiseases) {
                    Disease disease1 = diseaseMapper.selectDiseaseByDiseaseId(disease.getDiseaseId());
                    disease1.setDepartmentId(disease.getDepartmentId());
                    diseases.add(disease1);
                }
                departmentVO.setDepartmentId(department1.getDepartmentId());
                departmentVO.setDepartmentType(department1.getDepartmentType());
                departmentVO.setDiseaseList(diseases);
                departmentVOS.add(departmentVO);
            }
        } else {
            List<Disease> diseases = diseaseMapper.selectDiseaseByLikeIllness(illness);
            if (diseases != null) {
                for (Disease disease : diseases) {
                    DepartmentDisease departmentDisease = departmentDiseaseMapper.selectDepartmentDiseaseByDiseaseId(disease.getDiseaseId());
                    if (departmentDisease == null) {
                        continue;
                    }
                    Department department = departmentMapper.selectDepartmentByDepartmentId(departmentDisease.getDepartmentId());
                    if (department == null) {
                        continue;
                    }
                    // 查找该科室是否已经存在于结果集中
                    DepartmentVO existVO = null;
                    for (DepartmentVO vo : departmentVOS) {
                        if (vo.getDepartmentId().equals(department.getDepartmentId())) {
                            existVO = vo;
                            break;
                        }
                    }
                    if (existVO != null) {
                        // 已存在此科室，直接加入病种
                        existVO.getDiseaseList().add(disease);
                    } else {
                        // 不存在该科室，新建并加入
                        DepartmentVO departmentVO = new DepartmentVO();
                        departmentVO.setDepartmentId(department.getDepartmentId());
                        departmentVO.setDepartmentType(department.getDepartmentType());
                        List<Disease> diseaseList = new ArrayList<>();
                        diseaseList.add(disease);
                        departmentVO.setDiseaseList(diseaseList);
                        departmentVOS.add(departmentVO);
                    }
                }
            }
        }
        departmentVOS.sort((a, b) -> {
            String aType = PinyinUtil.getPinyinFirstChar(a.getDepartmentType());
            String bType = PinyinUtil.getPinyinFirstChar(b.getDepartmentType());
            return aType.compareTo(bType);
        });
        return AjaxResult.success(departmentVOS);
    }


    /**
     * 导入科室
     *
     * @param file
     * @return
     */
    @Override
    public AjaxResult addFile(MultipartFile file) throws IOException {
        ExcelUtil<Department> util = new ExcelUtil<>(Department.class);
        List<Department> departmentList = util.importExcel(file.getInputStream());
        // 先对 diseaseList 中的 illnessName 和 departmentName 去前后空格
        departmentList.forEach(department -> {
            if (department.getDepartmentType() != null) {
                department.setDepartmentType(department.getDepartmentType().trim());
            }
        });
        // 👉 1. Excel 内部去重（根据 departmentType 去重，保留第一条）
        Map<String, Department> uniqueExcelMap = departmentList.stream()
                .filter(dept -> StringUtils.isNotBlank(dept.getDepartmentType()))
                .collect(Collectors.toMap(
                        Department::getDepartmentType,
                        dept -> dept,
                        (existing, replacement) -> existing // 重复时保留第一个
                ));

        List<Department> uniqueExcelList = new ArrayList<>(uniqueExcelMap.values());

        // 👉 2. 查询数据库已有的科室列表
        List<Department> existingDepartments = departmentMapper.selectDepartmentList(new Department());

        // 👉 3. 提取已有的 departmentType
        Set<String> existingTypes = existingDepartments.stream()
                .map(Department::getDepartmentType)
                .filter(StringUtils::isNotBlank)
                .collect(Collectors.toSet());

        // 👉 4. 过滤掉数据库中已存在的类型
        List<Department> newDepartments = uniqueExcelList.stream()
                .filter(dept -> !existingTypes.contains(dept.getDepartmentType()))
                .collect(Collectors.toList());

        // 👉 5. 插入新数据
        for (Department dept : newDepartments) {
            String firstPinyinChar = PinyinUtil.getFirstPinyinChar(dept.getDepartmentType());
            dept.setSort(firstPinyinChar);
            departmentMapper.insertDepartment(dept);
        }

        return AjaxResult.success("导入成功，共导入 " + newDepartments.size() + " 条新数据");
    }


}
